// HotPostServiceImpl.java
package com.scuec.groupfive.service.impl;

import com.scuec.groupfive.entity.Post;
import com.scuec.groupfive.mapper.HotPostMapper;
import com.scuec.groupfive.service.HotPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;

@Service
public class HotPostServiceImpl implements HotPostService {

    @Autowired
    private HotPostMapper hotPostMapper;

    @Override
    public List<Post> getHotPosts(int page, int pageSize) {
        int offset = (page - 1) * pageSize;
        return hotPostMapper.getHotPostsWithPagination(offset, pageSize);
    }

    @Override
    public List<Post> getHotPostsByDateRange(Date startDate, Date endDate, int page, int pageSize) {
        int offset = (page - 1) * pageSize;
        return hotPostMapper.getHotPostsByDateRangeWithPagination(startDate, endDate, offset, pageSize);
    }

    @Override
    public double calculateHotScore(Long postId) {
        Post post = hotPostMapper.getPostById(postId);
        if (post == null) {
            return 0.0;
        }

        int viewCount = hotPostMapper.getViewCountByPostId(postId);
        int commentCount = hotPostMapper.getCommentCountByPostIdAndUser(postId, post.getUserId());
        int likeCount = hotPostMapper.getLikeCountByPostIdAndUser(postId, post.getUserId());
        int favoriteCount = hotPostMapper.getFavoriteCountByPostIdAndUser(postId, post.getUserId());

        double baseScore = viewCount * 0.3 + commentCount * 0.25 +
                likeCount * 0.25 + favoriteCount * 0.2;

        // 时间衰减因子 - 与SQL中的计算保持一致 帖子越新，分数越高
        long diffInDays = (new Date().getTime() - post.getCreatedAt().getTime()) / (1000 * 60 * 60 * 24);
        double timeFactor = Math.max(0, 1 - diffInDays * 0.01); // 每天衰减1%

        return baseScore * timeFactor;
    }
}